<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
  },
}
</route>
<template>
  <wd-notify />
  <cooperate v-if="shenhe == 1" :joinPhone="joinPhone"></cooperate>
  <view v-else class="merchant-registration-page min-h-screen bg-gray-50 pb-12">
    <view class="relative bg-orange-500 text-white py-12 px-4 text-center">
      <view class="absolute inset-0 bg-gradient-to-r from-orange-600 to-orange-400 opacity-80"></view>
      <view class="relative z-10">
        <h1 class="text-2xl font-bold mb-2">成为邻里生活荟合作商家</h1>
        <view class="text-white/90">填写以下申请信息，加入我们的商家生态圈</view>
      </view>
    </view>

    <view class="bg-white rounded-lg shadow-md mx-4 -mt-6 p-2 relative z-10 mb-6">
      <view class="flex items-start">
        <Info class="w-5 h-5 text-orange-500 mt-0.5 mr-2 flex-shrink-0" />
        <view>
          <view class="text-gray-700 text-sm">
            <!-- 请确保您提供的营业执照、经营资质等信息真实有效，我们将在1-3个工作日内完成审核。 -->
            {{ join }}
          </view>
          <view class="text-orange-500 font-medium mt-2">
            <!-- 入驻咨询热线: 400-888-9999 -->
            {{ joinPhone }}
          </view>
        </view>
      </view>
    </view>

    <view class="bg-white rounded-lg shadow-md mx-4 p-6">
      <view class="text-xl font-bold text-gray-800 mb-6">入驻申请表</view>

      <!-- 表单 -->
      <wd-form ref="formRef" :model="form">
        <wd-cell-group :border="true">
          <wd-input label="商家名称" label-width="100px" prop="name" clearable v-model="form.name" placeholder="请输入商家名称"
            :rules="[{ required: true, message: '请填写商家名称' }]" />

          <view class="flex pad">
            <text class="text-sm w-[100px]">
              <text class="text-red">*</text>
              门头照
            </text>
            <wd-upload label="门头照" :file-list="fileList" image-mode="aspectFill" :action="action" @change="handleChange"
              :limit="10" name="image"></wd-upload>
          </view>

          <wd-select-picker label="商家分类" v-model="form.classification" type="radio" prop="classification"
            placeholder="请选择商家分类" label-key="cateName" value-key="id" :rules="[{ required: true, message: '请选择商家分类' }]"
            :columns="categoryList"></wd-select-picker>

          <wd-input label="联系电话" label-width="100px" prop="telephone" clearable v-model="form.telephone"
            placeholder="请输入联系电话" :rules="[{ required: true, message: '请填写联系电话' }]" />

          <wd-textarea label="店铺简介" label-width="100px" prop="details" v-model="form.details" placeholder="请填写店铺简介"
            :rules="[{ required: true, message: '请填写店铺简介' }]" />

          <wd-col-picker label="选择地址" v-model="provinceCityArea" :columns="area" :column-change="columnChange"
            @confirm="handleConfirm" :display-format="displayFormat" placeholder="请选择商家地址"
            :rules="[{ required: true, message: '请选择商家地址' }]"></wd-col-picker>

          <wd-textarea label="详细地址" label-width="100px" prop="address" v-model="address" placeholder="请填写详细地址"
            :rules="[{ required: true, message: '请填写商家地址' }]" />

          <wd-checkbox v-model="agree">同意《用户隐私协议》和《服务协议》</wd-checkbox>
        </wd-cell-group>
        <view class="mt-2">
          <wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
        </view>
      </wd-form>
    </view>
  </view>
</template>

<script setup>
import { http } from '@/utils/http'
import { ref, reactive } from 'vue'
import { useNotify } from 'wot-design-uni'
import cooperate from "@/components/cooperate/index.vue"
import { useColPickerData } from '@/hooks/useColPickerData'

const { colPickerData, findChildrenByCode } = useColPickerData()

const join = ref('')
const joinPhone = ref('')
const shenhe = ref(1)

const getConfig = async () => {

  let res2 = await http.get('/api/config/list', {
    code: 'shenhe',
  })
  if (res2.code == 200) {
    shenhe.value = Number(res2.data.list[0].value)
    console.log('%c [ shenhe.value ]-101', 'font-size:13px; background:#333333; color:#f3f3f3;', shenhe.value)
  }

  let res = await http.get('/api/config/list', {
    code: 'join',
  })
  if (res.code == 200) {
    join.value = res.data.list[0].value
  }

  let res1 = await http.get('/api/config/list', {
    code: 'joinPhone',
  })
  if (res1.code == 200) {
    joinPhone.value = res1.data.list[0].value
  }
}
getConfig()

const area = ref([
  colPickerData.map((item) => {
    return {
      value: item.value,
      label: item.text,
    }
  }),
])

const columnChange = ({ selectedItem, resolve, finish }) => {
  const areaData = findChildrenByCode(colPickerData, selectedItem.value)
  if (areaData && areaData.length) {
    resolve(
      areaData.map((item) => {
        return {
          value: item.value,
          label: item.text,
        }
      }),
    )
  } else {
    finish()
  }
}

function handleConfirm(result) {
  provinceCityArea.value = result.selectedItems
}

const formRef = ref(null)
const categoryList = ref(null)
const form = reactive({
  address: '',
  classification: '',
  details: '',
  dimension: '',
  legalPerson: '',
  longitude: '',
  name: '',
  picture: '',
  remarks: '',
  telephone: '',
})
const agree = ref(false)

const { showNotify, closeNotify } = useNotify()

const action = import.meta.env.VITE_SERVER_BASEURL + '/api/file/uploadImage'

const initForm = async () => {
  let res = await http.get('/api/home/categories')

  if (res.code == 200) {
    categoryList.value = res.data.categories
  }
}

const provinceCityArea = ref([])
const address = ref('')

const handleChange = ({ fileList }) => {
  form.picture = fileList.map((item) => JSON.parse(item.response).url).join(',')
}

const displayFormat = (selectedItems) => {
  return selectedItems.map((item) => item.value.label).join('-')
}

const key = 'fbacb26edf56429309b33c7ed0e37d0b'
// 江西省上饶市信州区江光小区1栋1单元
const handleSubmit = async () => {
  let provinceCityAreaValue = provinceCityArea.value.map((item) => item.label).join('-')

  // 获取经纬度
  let resp = await uni.request({
    url: `https://restapi.amap.com/v3/geocode/geo?key=${key}&address=${provinceCityAreaValue} ${address.value}`,
    method: 'GET',
    header: {
      authorization: null,
      'sec-ch-ua': null,
      'sec-ch-ua-mobile': null,
      'sec-ch-ua-platform': null,
    },
  })

  if (resp.data.status == 1) {
    let location = resp.data.geocodes[0].location

    form.longitude = location.split(',')[0]
    form.dimension = location.split(',')[1]
  } else {
    uni.showToast({
      title: '请重新填写正确地址',
      icon: 'none',
      mask: false,
    })
    return
  }

  let res = await http.get('/api/store/add', {
    ...form,
    address: `${provinceCityAreaValue} ${address.value}`,
  })
  if (res.code === 200) {
    showNotify('提交成功')
    setTimeout(() => {
      uni.switchTab({ url: '/pages/mine/index' })
    }, 3000)
  } else {
    showNotify(res.msg)
  }
}

onLoad(() => {
  initForm()
})

onShareAppMessage(() => {
  return {
    title: '邻里生活荟',
    path: '/pages/join/index',
  }
})
onShareTimeline(() => {
  return {
    title: '邻里生活荟',
    path: '/pages/join/index',
  }
})
</script>

<style scoped>
.pad {
  padding: 20rpx 30rpx;
}
</style>
